/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { ChildLineCommandProps } from './types';
import { usePointContext } from './PointContext';

type FormDataType = {
  point?: pickedVertexData;
  distance: number;
  surface: pickedFaceData;
  vector: pickedLineData | pickedFaceData;
};

export function PointSurface({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) {
  const [formData, setFormData] = useState<FormDataType>({
    point: null,
    surface: null,
    distance: 0,
    vector: null,
  });

  const { picker } = useTools();
  const { setSharedPoint } = usePointContext();

  useEffect(() => {
    executeData();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const point = props?.params?.point;
      const surface = props?.params?.surface;
      const distance = props?.params?.distance;
      const vector = props?.params?.vector;

      await initEditDependency([point, surface, vector]);

      setFormData({
        point: point
          ? (picker.generatePickObjByPickID(point) as pickedVertexData)
          : null,
        surface: picker.generatePickObjByPickID(surface) as pickedFaceData,
        vector: picker.generatePickObjByPickID(vector) as
          | pickedLineData
          | pickedFaceData,
        distance: distance,
      });
    }
  }, [editDxid, props]);

  const isFormDataValid = () => {
    const { distance, surface, vector } = formData;
    return vector !== null && surface !== null && distance !== null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await executeData(false);
    onClose();
  };

  const {
    previewCmdResult,
    initEditDependency,
    initingEdit,
    isLoading,
    clear,
    confirmCommand,
  } = useCommand('cmd-surface-point', {
    onClose,
    finishDraw: checkAndFinishDraw,
    commandName: 'CreateVertex',
    editDxid: editDxid || props?.shape,
  });

  useEffect(() => {
    const pointdata = previewCmdResult?.data?.[0]?.points?.[0];
    if (pointdata) {
      setSharedPoint(pointdata);
    } else {
      setSharedPoint(null);
    }
  }, [previewCmdResult]);

  const executeData = async (preview: boolean = true) => {
    const { point, vector, distance, surface } = formData;

    if (!isFormDataValid()) {
      clear();
      return;
    }

    const allParma = {
      a: {
        mode: 'onsurface',
        surface: surface?.meshId,
        distance: distance,
        vector: getIdOfPickedObj(vector),
        point: point?.vertexId,
      },
      p: preview,
    };

    await confirmCommand(allParma, preview);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      point: {
        type: 'string',
        title: '参考点',
        format: PickInputRJSFFormat.PickVertex,
      },
      surface: {
        type: 'string',
        title: '曲面',
        format: PickInputRJSFFormat.PickSurface,
      },
      vector: {
        type: 'string',
        title: '方向',
        format: PickInputRJSFFormat.PickDirection,
      },
      distance: {
        type: 'number',
        title: '距离',
        default: 0,
        format: NumberInputFormat.Length,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      onCancel={onClose}
      disabled={initingEdit}
      submitLoading={isLoading}
      isFormDataValid={isFormDataValid()}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        const data = {
          point: v.point,
          distance: v.distance,
          surface: v.surface,
          vector: v.vector,
        };
        setFormData(data);
      }}
      extraUiSchema={{
        point: {
          'ui:placeholder': '请选择，默认面心',
        },
        surface: {
          'ui:placeholder': '请输入曲面',
          'ui:autofocus': true,
        },
        vector: {
          'ui:placeholder': '方向',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}
